package com.zbd.microservices.config;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

import com.zbd.microservices.security.AuthoritiesConstants;

@Configuration
@EnableResourceServer
public class OauthResouceServerConfig extends ResourceServerConfigurerAdapter {
	@Inject
	TokenStore tokenStore;

	@Override
	public void configure(HttpSecurity http) throws Exception {
		http
		.exceptionHandling()
		.authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
		.and()
		.csrf()
		.disable()
		.headers()
		.frameOptions()
		.disable()
		.and()
		.sessionManagement()
		.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
		.and()
		.authorizeRequests()
		.antMatchers("/api/register").permitAll()
		.antMatchers("/api/activate").permitAll()
		.antMatchers("/api/authenticate").permitAll()
		.antMatchers("/api/account/reset_password/init").permitAll()
		.antMatchers("/api/account/reset_password/finish").permitAll()
		.antMatchers("/api/profile-info").permitAll()
		.antMatchers("/api/**").authenticated()
		.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
		.antMatchers("/v2/api-docs/**").permitAll()
		.antMatchers("/swagger-resources/configuration/ui").permitAll()
		.antMatchers("/swagger-ui/index.html").authenticated();
	}

	@Override
	public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
		resources.resourceId("UAA").tokenStore(tokenStore);
	}
}

